var _token = null;
const HTTP_EXP = /^http.+$/;
// const URL = 'http://localhost:3715/';
const URL = 'https://bd.fengyitong.name/';
const PAGE_SIZE = 5;  //每次加载数量.
var _token_callback = null;

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const request = config => {
  if (!config.header) config.header = {};
  if (_token != null) config.header.Authorization = 'Bearer ' + _token;
  if (!HTTP_EXP.test(config.url)) config.url = URL + config.url;
  const callback = config.success;
  config.success = rst => {
    typeof callback === 'function' && callback(rst.data, rst);
  }
  if (!config.fail) {
    config.fail = () => {
      wx.showToast({
        title: '读取数据失败',
        icon: 'none'
      });
    }
  }
  return wx.request(config);
};

//错误提示框 
const errMessage = (msg, callback) => {
  wx.showModal({
    // title: '',
    content: msg,
    showCancel: false,
    success: res => {
      typeof callback === 'function' && callback(res);
    }
  })
}

const err = (msg = '失败', code = -1, data = null) => {
  const rst = {
    message: msg,
    code: code
  }
  if (data != null) rst.data = data;
  return rst;
}

const setToken = token => {
  _token = token;
  _tokenCall();
}

const ready = callback => {
  _token_callback = callback;
  _tokenCall();
}

function _tokenCall() {
  _token && typeof _token_callback === 'function' && _token_callback(_token);
}


module.exports = {
  formatTime,   //格式化时间
  errMessage,   //错误弹框
  request,      //二次封装微信请求
  setToken,     //初始化jwt令牌
  ready,        //回调.(正确获取到令牌口令.)
  err,          //模拟服务端错误返回
  URL,
  PAGE_SIZE
}
